package com.itheima.utils;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

/**
 * @author junmanna
 * @version 1.0
 * @date 2019/11/10 18:35
 */
@Component
public class UpAndDown {
    public static String upload(MultipartFile myFile, HttpServletRequest request){
        String myFilePath = "";
        if(!myFile.isEmpty()){
            try{
                String fileName = myFile.getOriginalFilename();
                fileName = UUID.randomUUID().toString().replace("-","")+fileName.substring(fileName.lastIndexOf("."));
                //文件路径：绝对路径，获取应用内部目录或图片服务器的物理路径
                //以下是上传到服务器下（非图片服务器）
                myFilePath = request.getSession().getServletContext().getRealPath("")+"images\\"+fileName;
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(myFilePath)));
                out.flush();
                out.close();
                myFilePath = "images\\" + fileName;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return myFilePath;
    }
}
